'=====================================================================
'
'  File:    Catalog.vb for Product Catalog XML Example
'  Summary: Winform for displaying a product catalog stored in
'			the AdventureWorks OLTP database.
'  Date:    January 20, 2006
'
'---------------------------------------------------------------------
'  This file is part of the Microsoft SQL Server Code Samples.
'  Copyright (C) Microsoft Corporation.  All rights reserved.
'
'  This source code is intended only as a supplement to Microsoft
'  Development Tools and/or on-line documentation.  See these other
'  materials for detailed information regarding Microsoft code samples.
'
'  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
'  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
'  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
'  PARTICULAR PURPOSE.
'======================================================= 

''' <summary>
''' Summary description for form.
''' </summary>

Partial Public Class Catalog 'The Partial modifier is only required on one class definition per project.
    Inherits Form
    Private Const prettyXmlXsltFileName As String = "..\..\defaultss.xslt"
    Private Const descriptionXsltFileName As String = "..\..\ProductDescription.xsl"

    ''' <summary>
    ''' Required designer variable.
    ''' </summary>
    Public Sub New()
        InitializeComponent()
    End Sub

    Private Shared Function GetSoapRequestXml(ByVal productModelID As Integer) As String
        Return "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" + "  <soap:Body>" + "    <GetProductDescription xmlns='testns'>" + "      <ProductModelID>" + productModelID.ToString(CultureInfo.InvariantCulture) + "</ProductModelID>" + "    </GetProductDescription>" + "  </soap:Body>" + "</soap:Envelope>"
    End Function

    Private Shared Function PostSoapRequest(ByVal requestXml As String) As Stream
        Dim soapWebRequest As HttpWebRequest = CType(WebRequest.Create("http://localhost/ProductCatalog/"), HttpWebRequest)
        soapWebRequest.Accept = "text/xml"
        soapWebRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "identity, gzip;q=0")
        soapWebRequest.ContentType = "text/xml"
        soapWebRequest.CachePolicy = New RequestCachePolicy(RequestCacheLevel.NoCacheNoStore)
        soapWebRequest.Headers.Add("SOAPAction", "")
        soapWebRequest.Credentials = CredentialCache.DefaultCredentials
        soapWebRequest.Method = "POST"

        Dim webStream As Stream = soapWebRequest.GetRequestStream()
        Using webWriter As New StreamWriter(webStream)
            webWriter.Write(requestXml)
            webWriter.Flush()
        End Using

        Dim response As WebResponse = soapWebRequest.GetResponse()
        Return response.GetResponseStream()
    End Function

    <System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")> _
    Private Sub ShowDescriptionButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ShowDescriptionButton.Click
        Try
            Dim productModelID As Integer = Integer.Parse(ProductModelIDTextBox.Text, CultureInfo.InvariantCulture)
            Dim requestXML As String = GetSoapRequestXml(productModelID)
            Using webResponseStream As Stream = PostSoapRequest(requestXML)
                Dim xslt As New XslCompiledTransform()
                Using xsltStreamReader As StreamReader = File.OpenText(descriptionXsltFileName)
                    Using xsltXmlReader As XmlReader = XmlReader.Create(xsltStreamReader)
                        xslt.Load(xsltXmlReader)
                    End Using
                End Using

                Dim xmlResults As New XPathDocument(webResponseStream)
                Dim navigator As XPathNavigator = xmlResults.CreateNavigator()
                Dim namespaces As New XmlNamespaceManager(navigator.NameTable)
                namespaces.AddNamespace("z", "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription")

                Dim expr As XPathExpression = navigator.Compile("//z:ProductDescription")
                expr.SetContext(namespaces)
                Dim iterator As XPathNodeIterator = navigator.Select(expr)
                If iterator.Count = 0 Then
                    webBrowser1.DocumentText = String.Format(System.Globalization.CultureInfo.InvariantCulture, "<BODY>Product {0} not found.<BODY>", productModelID)
                Else
                    Dim resultStringWriter As New StringWriter(CultureInfo.InvariantCulture)
                    Dim resultXmlWriter As New XmlTextWriter(resultStringWriter)
                    Try

                        If iterator.MoveNext() Then
                            xslt.Transform(iterator.Current.Clone(), New XsltArgumentList(), resultXmlWriter)
                        End If

                        resultXmlWriter.Flush()
                    Finally
                        resultXmlWriter.Close()
                    End Try

                    webBrowser1.DocumentText = resultStringWriter.ToString()
                End If
            End Using
        Catch exception As System.Exception
            webBrowser1.DocumentText = exception.ToString()
        End Try
    End Sub

    <System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")> _
    Private Sub ShowResponseButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ShowResponseButton.Click
        Try
            Dim productModelID As Integer = Integer.Parse(ProductModelIDTextBox.Text, CultureInfo.InvariantCulture)
            Dim requestXML As String = GetSoapRequestXml(productModelID)
            Using webResponseStream As Stream = PostSoapRequest(requestXML)
                Dim xmlResults As New XPathDocument(webResponseStream)
                TransformAndBrowseDocument(xmlResults)
            End Using
        Catch exception As System.Exception
            webBrowser1.DocumentText = exception.ToString()
        End Try
    End Sub

    <System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")> _
    Private Sub ShowRequestButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ShowRequestButton.Click
        Try
            Dim productModelID As Integer = Integer.Parse(ProductModelIDTextBox.Text, CultureInfo.InvariantCulture)
            TransformAndBrowseDocument(GetSoapRequestXml(productModelID))
        Catch exception As System.Exception
            webBrowser1.DocumentText = exception.ToString()
        End Try
    End Sub

    <System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")> _
    Private Sub ShowXSLButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ShowXSLButton.Click
        Try
            Using fs As StreamReader = File.OpenText(descriptionXsltFileName)
                If (True) Then
                    TransformAndBrowseDocument(fs.ReadToEnd())
                End If
            End Using
        Catch exception As System.Exception
            webBrowser1.DocumentText = exception.ToString()
        End Try
    End Sub

    Private Overloads Sub TransformAndBrowseDocument(ByVal xmlDocument As String)
        Using sr As New StringReader(xmlDocument)
            Using xtr As New XmlTextReader(sr)
                Dim doc As New XPathDocument(xtr)
                TransformAndBrowseDocument(doc)
            End Using
        End Using
    End Sub

    Private Overloads Sub TransformAndBrowseDocument(ByVal doc As XPathDocument)
        Dim xslt As New XslCompiledTransform()
        Using xsltStreamReader As StreamReader = File.OpenText(prettyXmlXsltFileName)
            Using xsltXmlReader As XmlReader = XmlReader.Create(xsltStreamReader)
                xslt.Load(xsltXmlReader)
            End Using
        End Using

        Dim resultStringWriter As New StringWriter(CultureInfo.InvariantCulture)
        Dim resultXmlWriter As New XmlTextWriter(resultStringWriter)

        Try
            xslt.Transform(doc, New XsltArgumentList(), resultXmlWriter)
            resultXmlWriter.Flush()
        Finally
            resultXmlWriter.Close()
        End Try

        webBrowser1.DocumentText = resultStringWriter.ToString()
    End Sub
End Class
